# -*- coding: utf-8 -*-
import sys

sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
from urllib.parse import urlencode
import requests
from common.helper import Helper
from pprint import pprint


class Spider(object):
    def __init__(self):

        self.mysql = MysqlClient()
        self.name = "健康保重大疾病保险(至尊版)保险产品计划"

    # 生成产品数据
    def genProductInfo(self):
        plan = {
            "planA": {
                "year": [str(i) for i in range(0, 46)],
                "gender": ["M", "F"],
                "money": ["100000", "200000", "300000", "400000", "500000", "600000"],
                "expire": ["终身"],
                "payType": ["年缴"],
                "interval": ["20"],
                # 附加险：轻症疾病保险金 0 不投保 1 投保
                "ext_item": ["0", "1"]
            },
            "planB": {
                "year": [str(i) for i in range(46, 46)],
                "gender": ["M", "F"],
                "money": ["100000", "200000", "300000"],
                "expire": ["终身"],
                "payType": ["年缴"],
                "interval": ["20"],
                # 附加险：轻症疾病保险金 0 不投保 1 投保
                "ext_item": ["0", "1"]
            }
        }
        for k in plan:
            for v in product(plan[k]["year"], plan[k]["gender"], plan[k]["money"], plan[k]["expire"],
                             plan[k]["payType"], plan[k]["interval"], plan[k]["ext_item"]):
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(

                    v[0], v[1], v[2], v[3], v[4], v[5], v[6]
                ))
                self.mysql._conn.commit()
                print(
                    domain[self.name]["insert_sql"].format(

                        v[0], v[1], v[2], v[3], v[4], v[5], v[6]
                    )
                )

    # 执行爬虫
    def requestJson(self, dt=None):

        dt = self.mysql.randTask(self.name)

        params = {
            "year": str(2020 - int(dt["year"])),
            "sex": "0" if dt["gender"] == "M" else "1",
            "money": dt["money"]
        }
        # 附加险不投保
        if dt["ext_item"] == "0":

            print("额外附加险不进行投保~~~")

            data = {

                "insuredsStr": '[{"birthday":"'+params["year"]+'-01-01","sex":"'+params["sex"]+'","planInfos":[{"riskCode":"I141","mainRiskCode":"I141","planCode":"27","planPeriod":"终身","payType":"12","payEndYearFlag":"Y","payEndYear":20,"dutys":[{"dutyCode":"141001","dutyAmnt":"'+params["money"]+'"}]}]}]',
                "isOrder": "0",
                "productID": "35"

            }

        else:
            print("额外附加险进行投保~~~")

            data = {
                "insuredsStr": '[{"birthday":"' + params["year"] + '-01-01","sex":"'+params["sex"]+'","planInfos":[{"riskCode":"I141","mainRiskCode":"I141","planCode":"27","planPeriod":"终身","payType":"12","payEndYearFlag":"Y","payEndYear":20,"dutys":[{"dutyCode":"141001","dutyAmnt":"'+params["money"]+'"}]},{"riskCode":"I142","mainRiskCode":"I141","planCode":"28","planPeriod":"终身","payType":"12","payEndYearFlag":"Y","payEndYear":20,"dutys":[{"dutyCode":"142001","dutyAmnt":"'+params["money"]+'"}]}]}]',
                "isOrder": "0",
                "productID": "31",

            }

        payload = urlencode(data).replace('+', '')

        r = requests.post(url=domain[self.name]["url"], headers=domain[self.name]["header"], data=payload)

        print( r.json())

        if r.status_code == 200 and r.json()["data"]["code"] == 200:

            price = Helper.decimalParse(r.json()["data"]["data"]["insureds"][0]["insurerPrem"])

            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )

        else:

            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )
            print("/*保险产品信息更新失败:%d*/"%dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return
            # 任务执行状态
            data = {

                "name": self.name,

                "id": dt["id"],

                "state": 1

            }
            self.mysql.updateTask(data)

            self.requestJson(dt)
